/**   
 * @Title: SecurityUtil.java 
 * @Package com.org.framework.secret 
 * @Description: TODO(用一句话描述该文件做什么) 
 * @author cssuger@163.com   
 * @date 2017年1月22日 下午3:40:38 
 * @version V1.0   
 */
package com.bicon.base.data.common.secret;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import com.bicon.base.data.common.UUIDGenerator;
import com.bicon.base.data.common.tools.DateUtil;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * @ClassName: SecurityUtil
 * @Description: 该类里面包含md5加密，des3加密算法
 * @author cssuger@163.com
 * @date 2017年1月22日 下午3:40:38
 */
public class SecurityUtil {

	public static final String KEY = "asdfghjklzxcvbnmqwertyuiop1234567890ASDFGHJKLQWERTYUIOPZXCVBNM!@#$%^&*()";

	// 算法名称
	public static final String KEY_ALGORITHM = "DES";
	// 算法名称/加密模式/填充方式
	// DES共有四种工作模式-->>ECB：电子密码本模式、CBC：加密分组链接模式、CFB：加密反馈模式、OFB：输出反馈模式
	public static final String CIPHER_ALGORITHM = "DES/ECB/NoPadding";

	private static String md5(byte[] input) {
		return DigestUtils.md5Hex(input);
	}

	public static String md5(String input) {
		return new String(md5(input.getBytes()));
	}

	/**
	 * @throws UnsupportedEncodingException
	 * 
	 * @Title: base64encode
	 * @Description: 64位编码
	 * @param @param input
	 * @param @return 设定文件
	 * @return byte[] 返回类型
	 * @throws
	 */
	public static byte[] base64encode(String input) {

		try {
			return Base64.encodeBase64(input.getBytes("UTF-8"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static byte[] base64encode(byte[] input) {

		try {
			return Base64.encodeBase64(input);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * @Title: base64decode
	 * @Description: 64位解码
	 * @param @param input
	 * @param @return 设定文件
	 * @return byte[] 返回类型
	 * @throws
	 */
	public static byte[] base64decode(String input) {
		try {
			return Base64.decodeBase64(input.getBytes("UTF-8"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 加密
	 * 
	 * @param content
	 *            需要加密的内容
	 * @param password
	 *            加密密码
	 * @return
	 */
	public static byte[] encrypt(String content, String password) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
			random.setSeed(password.getBytes());
			kgen.init(128,random);
			//kgen.init(128, new SecureRandom(password.getBytes()));//window上没有问题，但是在linux上存在问题
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");// 创建密码器
			byte[] byteContent = content.getBytes();
			cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
			byte[] result = cipher.doFinal(byteContent);
			return result; // 加密
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 解密
	 * 
	 * @param content
	 *            待解密内容
	 * @param password
	 *            解密密钥
	 * @return
	 */
	public static byte[] decrypt(byte[] content, String password) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			kgen.init(128, new SecureRandom(password.getBytes()));
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");// 创建密码器
			cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
			byte[] result = cipher.doFinal(content);
			return result; // 加密
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 将二进制转换成16进制
	 * 
	 * @param buf
	 * @return
	 */
	public static String parseByte2HexStr(byte buf[]) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < buf.length; i++) {
			String hex = Integer.toHexString(buf[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}

	/**
	 * 将16进制转换为二进制
	 * 
	 * @param hexStr
	 * @return
	 */
	public static byte[] parseHexStr2Byte(String hexStr) {
		if (hexStr.length() < 1)
			return null;
		byte[] result = new byte[hexStr.length() / 2];
		for (int i = 0; i < hexStr.length() / 2; i++) {
			int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
			int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
					16);
			result[i] = (byte) (high * 16 + low);
		}
		return result;
	}

	/**
	 * @param str
	 * @return String
	 * 讲一个字符串进行MD5加密
	 */
	public static String getMD5(String str){
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(str.getBytes());
			return new BigInteger(1,md.digest()).toString(16);
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		}
		return str;
	}
	
	/**
	 * 
	 * @Title: getSlot   
	 * @Description: 进行加盐操作   
	 * @param: @param input
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	public static String getSlot(String input) {
		return getMD5( new UUIDGenerator().generate().toString()+input+DateUtil.now(DateUtil.format4));
	}
	public static void main(String[] args) throws Exception {
		System.out.println(new String(base64encode("ykt")));
		//String content = "bus2";
		String content = "test_ykt";  
		//String password = "12345678";  
		//加密  
		System.out.println("加密前：" + content);  
		byte[] encryptResult = encrypt(content, KEY);  
		String encryptResultStr = parseByte2HexStr(encryptResult);  
		System.out.println("加密后：" + encryptResultStr);  
		//解密  
		byte[] decryptFrom = parseHexStr2Byte(encryptResultStr);  
		byte[] decryptResult = decrypt(decryptFrom,KEY);  
		System.out.println("解密后：" + new String(decryptResult));  

	}
	
	/**
	 * 字符串转Base64（加密）
	 * @param str
	 * @return
	 */
    public static String getBase64(String str) {  
        byte[] b = null;  
        String s = null;  
        try {  
            b = str.getBytes("utf-8");  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        }  
        if (b != null) {  
            s = new BASE64Encoder().encode(b);  
        }  
        return s;  
    }  
  
    /**
     * Base64转字符串（解密）
     * @param s
     * @return
     */
    public static String getFromBase64(String s) {  
        byte[] b = null;  
        String result = null;  
        if (s != null) {  
            BASE64Decoder decoder = new BASE64Decoder();  
            try {  
                b = decoder.decodeBuffer(s);  
                result = new String(b, "utf-8");  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
        return result;  
    }  

}
